var requestParams = app.getRequestParams();

$(function(){

    $('#tabs').tabs({height:458});

    disableSetting(2000000004,'enableFine');
    disableSetting(2000000005,'enableBatch');
    disableSetting(2000000006,'enableStore');
    disableSetting(2000000007,'enableSn');

    $('#enableFine').click(enableFineClick);

    function enableFineClick(){
        var checked = $('#enableFine').prop('checked');
        if( checked ){
            $('input[n="fineDate"],label[n="fineDate"]').show();
        }else{
            $('input[n="fineDate"],label[n="fineDate"]').hide();
        }
    }

    $('#enableStore').click(enableStoreClick);

    function enableStoreClick(){
        var checked = $('#enableStore').prop('checked');
        if( checked ){
            $('input[n="storeWarning"],label[n="storeWarning"]').show();
        }else{
            $('input[n="storeWarning"],label[n="storeWarning"]').hide();
        }
    }



    $('#unitId').combobox({
        url:'unit/select',
        valueField:'id',textField:'name',
        name:'product.unitId',
        click:function(text,value){
            //alert(text+'-----------'+value);
        }
    });

    $('#productType').search({
        name:'product.productTypeId',
        click:function(){
            var index = parent.layer.getFrameIndex(window.name);
            app.window(parent.layer,{
                btn:[],
                area: ['800px', '600px'],
                content: '../../common/productype_tree.html?index='+index+'&searchId=productType&selectLeaf=0&idField=id'
            });
        }
    });

    $('#companyId').search({
        name:'product.companyId',
        click:function(){
            var index = parent.layer.getFrameIndex(window.name);
            app.window(parent.layer,{
                btn:[],
                area: ['800px', '600px'],
                content: '../../common/company_tree.html?index='+index+'&searchId=companyId'
            });
        }
    });

    $('#grid').datagrid({
        width:300,pagination:false,tableCss:{"margin":"0px"},
        columns:[
            {title:'操作',width:100,formatter:gridOpt},
            {field:'name',title:'辅助单位',width:100,edit:'text'},
            {field:'rate',title:'换算率',width:100,edit:'number'}
        ]
    });

    function gridOpt(row){
        var addSpan = $('<span class="fix-table-icon"><i class="fa fa-plus" style="color:green;"></i></span>');

        addSpan.click(function () {
            $('#grid').datagrid("loadData",{rows:[{xxid:app.DEFAULT_ALL_VALUE}]});
        });

        var delSpan = $('<span class="fix-table-icon"><i class="fa fa-remove" style="color:red;"></i></span></div>');
        delSpan.click(function () {
            var tr = $(this).parent().parent().parent();
            var len = tr.parent().find('.vui-table-row[type="body"]').length;
            if( len == 1 ){
                app.alert(parent.layer,'最后一行不能删除',2);
            }else{
                tr.remove();
            }
        });

        var outDiv = $('<div></div>');
        outDiv.append(addSpan).append(delSpan);;

        return outDiv;
    }

    if(requestParams.id){
        app.request({
            url:'product/get',
            data:{id:requestParams.id},
            success:function(resp){
                var product = resp.data.product;
                var productPrice = resp.data.productPrice;
                app.resetForm(addPropertyPrefix(product,'product.'));
                app.resetForm(addPropertyPrefix(productPrice,'productPrice.'));

                $('input[name="product.unitId_text"]').val(product.unitName);
                $('input[name="product.productTypeId_text"]').val(product.productTypeName);
                $('input[name="product.companyId_text"]').val(product.companyName);

                if(product.enableBatch==1){
                    $('#enableBatch').prop('checked',true);
                }
                if(product.enableFine==1){
                    $('#enableFine').prop('checked',true);
                    enableFineClick();
                }
                if(product.enableStore==1){
                    $('#enableStore').prop('checked',true);
                    enableStoreClick();
                }

                var units = resp.data.units;
                if( units && units.length > 0 ){
                    $('#grid').datagrid("loadData",{rows:units});
                }else{
                    $('#grid').datagrid("loadData",{rows:[{}]});
                }

                var productPrice = resp.data.productPrice;
                if(productPrice){
                    app.resetForm(addPropertyPrefix(productPrice,'productPrice.'));
                }
            }
        });
    }else{
        $('#companyId input[name="product.companyId_text"]').val(top.loginCompanyName);
        $('#companyId input[name="product.companyId"]').val(top.loginCompanyId);
        $('#grid').datagrid("addRow",{});
    }

    function addPropertyPrefix(o,prefix){
        var result = {};
        for( var n in o ){
            result[prefix+n] = o[n];
        }
        return result;
    }

    app.getOkBtn().click(function(){
        if( !checkForm() ){
            return;
        }

        var url = 'product/insert';
        if(requestParams.id){
            url = 'product/update'
        }

        var data = app.serializeForm();
        var index = 0;
        $('#grid .vui-table-row[type="body"]').each(function (i) {
            var name = $(this).find('.vui-table-cell[field="name"]').html();
            var rate = $(this).find('.vui-table-cell[field="rate"]').html();

            if(name.length>0 && rate.length>0){
                data['productMultiUnits['+index+'].name'] = name;
                data['productMultiUnits['+index+'].rate'] = rate;
                index++;
            }
        });

        setCheckbox(data,'enableBatch');
        setCheckbox(data,'enableFine');
        setCheckbox(data,'enableStore');

        app.request({
            url:url,
            data:data,
            success:function(resp){
                if( resp.result==0 ){
                    app.closeLastWindow();
                    app.message(parent.layer,'操作成功');
                    parent.$("#table").datagrid("reload");
                }else{
                    var message = top.bussError['code'+resp.result];
                    if(!message){
                        message = top.bussError['code'+resp.data];
                    }
                    if(!message){
                        message = resp.data;
                    }
                    app.message(parent.layer,'操作失败【'+message+'】',2);
                }
            }
        });


    });

    function setCheckbox(data,name){
        var checked = $('#'+name).prop('checked');
        if(checked){
            data['product.'+name] = 1;
        }else{
            data['product.'+name] = 0;
        }
    }

    function checkForm(){

        var checkOptions = [
            {type:'input',name:'product.name',verify:[{type:'required'}]},
            {type:'input',name:'product.code',verify:[{type:'required'}]},
            {type:'input',name:'product.productTypeId_text',verify:[{type:'required'}]},
            {type:'input',name:'product.unitId_text',verify:[{type:'required'}]},
            {type:'input',name:'product.model',verify:[{type:'length',value:20}]},
            {type:'input',name:'product.purchasePrice',verify:[{type:'decimal'}]},
            {type:'input',name:'product.salePrice',verify:[{type:'decimal'}]}
        ];

        return app.checkForm(checkOptions);
    }




    if(requestParams.id){

    }else{
        //var company = {"product.companyId":app.getCompanyId(),"product.companyId_text":app.getCompanyName()};
        //app.resetForm(company);
    }

});

function disableSetting(code,id) {
    if( app.getDictValue(code) == 0 ){
        $('#'+id).hide();
        $('label[for="'+id+'"]').hide();
    }
}